<template>
  <div class="app-container">
    <el-col style="width: 100%; align-items:center;" type="flex" justify="space-between">
      <el-row>
        <div style="margin-bottom: 20px;">
          <span style="font-size: 20px; font-weight: bold">个人信息</span>
        </div>
      </el-row>
      <el-card type="box-card" style="padding-left: 20px; padding-top: 20px;padding-bottom: 20px">
        <el-form ref="form" :model="form" label-position="left">
          <el-row style="align-items: center" type="flex">
            <el-col :span="8">
              <el-avatar class="avatar-class" shape="square" fit="fill" :size="88" :src="form.squareUrl" />
            </el-col>
            <el-col :span="8">
              <el-upload
                ref="uploadBtn"
                :http-request="uploadAvatar"
                class="upload-demo"
                action="123"
                :auto-upload="true"
                :show-file-list="false"
                accept=".jpg, .png"
              >
                <el-button size="small" icon="el-icon-upload2" plain>上传头像</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </el-col>
          </el-row>
          <el-row style="margin-top: 30px">
            <el-col :span="8">
              <span style="font-weight: bold">工号</span>
            </el-col>
            <el-col :span="8" style="color: #5a5e66">
              <span>{{ $store.getters.userInfo.uid }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-top: 30px">
            <el-col :span="8">
              <span style="font-weight: bold">姓名</span>
            </el-col>
            <el-col :span="8" style="color: #5a5e66">
              <span>{{ $store.getters.userInfo.name }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-top: 30px">
            <el-col :span="8">
              <span style="font-weight: bold">所属部门</span>
            </el-col>
            <el-col :span="8" style="color: #5a5e66">
              <span>{{ $store.getters.userInfo.name.group||'暂无部门' }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-top: 30px;">
            <el-col :span="8">
              <span style="font-weight: bold">我的签名</span>
            </el-col>
            <el-col :span="8" style="color: #5a5e66">
              <sign ref="trueSign" :simple="true" style="width: 128px;" :img="`${signImg}`" @submit="changeSign" />
            </el-col>
            <el-col :span="8" style="color: #5a5e66" />
          </el-row>
          <!--          <el-row style="margin-top: 30px">-->
          <!--            <el-col :span="8">-->
          <!--              <span style="font-weight: bold">手机号码</span>-->
          <!--            </el-col>-->
          <!--            <el-col :span="8" style="color: #5a5e66">-->
          <!--              <span>12345678</span>-->
          <!--            </el-col>-->
          <!--            <el-col :span="8" style="color: #5a5e66">-->
          <!--              <el-button size="small" icon="el-icon-edit">更改</el-button>-->
          <!--            </el-col>-->
          <!--          </el-row>-->
          <!--          <el-row style="margin-top: 30px">-->
          <!--            <el-col :span="8">-->
          <!--              <span style="font-weight: bold">邮箱</span>-->
          <!--            </el-col>-->
          <!--            <el-col :span="8" style="color: #5a5e66">-->
          <!--              <span>zhangsan@163.com</span>-->
          <!--            </el-col>-->
          <!--            <el-col :span="8" style="color: #5a5e66">-->
          <!--              <el-button size="small" icon="el-icon-edit" @click="changeEmail">更改</el-button>-->
          <!--            </el-col>-->
          <!--          </el-row>-->
          <el-row style="margin-top: 30px;">
            <el-col :span="8">
              <span style="font-weight: bold">账户密码</span>
            </el-col>
            <el-col :span="8" style="color: #5a5e66">
              <span>已设置</span>
            </el-col>
            <el-col :span="8" style="color: #5a5e66">
              <el-button size="small" icon="el-icon-edit" @click="dialogFormVisible = true">更改</el-button>
              <el-dialog title="修改密码" :visible.sync="dialogFormVisible">
                <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px"
                         class="demo-ruleForm"
                >
                  <el-form-item label="设置新密码" prop="pass">
                    <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="checkPass">
                    <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="dialogFormVisible = false">取 消</el-button>
                  <el-button type="primary" @click="changePWD">确 定</el-button>
                </div>
              </el-dialog>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </el-col>
  </div>
</template>

<script>

import { postAvatar, changePassword, updateSign } from '@/api/user'
import Sign from '@/components/Sign/index'
import { BASE_URL } from '@/utils/request'
export default {
  name: 'MyInfo',
  components: { Sign },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度请大于6位'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度请大于6位'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      signData: '',
      BASE_URL: BASE_URL,
      signImg: this.$store.getters.userInfo.sign_img,
      form: {
        squareUrl: this.$store.getters.avatar,
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      dialogFormVisible: false,
      ruleForm: {
        pass: '',
        checkPass: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    signData(newVal, oldVal) {
      const file = this.dataURLtoFile(newVal, 'sign.jpg')
      const formData = new FormData()
      formData.append('file', file)
      updateSign(formData).then(
        res => {
          window.location.reload()
        }
      )
    }
  },
  methods: {
    changeSign(s, base) {
      if (s !== 1) {
        const formData = new FormData()
        formData.append('file', s)
        updateSign(formData).then(
          res => {
            window.location.reload()
          }
        )
      }
    },
    dataURLtoFile(dataURL, fileName, fileType) {
      const arr = dataURL.split(',')
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], fileName, { type: fileType || 'image/jpg' })
    },
    changePWD() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          changePassword({ uid: this.$store.getters.userInfo.uid, password: this.ruleForm.pass }).then(res => {
            this.$message.success('修改密码成功！')
            this.dialogFormVisible = false
          })
        } else if (this.ruleForm.pass.length < 6) {
          this.$message.error('密码长度请大于6位。')
          return false
        } else {
          this.$message.error('两次密码不一致。')
          return false
        }
      })
    },
    uploadAvatar(param) {
      const x = new FormData()
      x.append('file', param.file)
      postAvatar(x).then(res => {
        const { data } = res
        this.form.squareUrl = process.env.VUE_APP_BASE_API + data
        this.$store.dispatch('user/getInfo')
      })
    },
    changeEmail() {
      this.$prompt('请输入邮箱', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: '邮箱格式不正确'
      }).then(({ value }) => {
        this.$message({
          type: 'success',
          message: '你的邮箱是: ' + value
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-avatar ::v-deep img {
  height: 100% !important;
  width: 100% !important;
}
</style>
